//
//  UrbanMainViewController.m
//  UrbanManagement
//
//  Created by Can on 18/4/8.
//  Copyright © 2018年 hwd. All rights reserved.
//

#import "UrbanMainViewController.h"
#import "UrbanHomeTableViewCell.h"
#import "UrbanWhereViewController.h"
#import "UrbanPhotoViewController.h"
#import "UrbanLawEnforcementViewController.h"
#import "UrbanPrinterViewController.h"
#import "UrbanPrinterViewController.h"
#import "UrbanBlueTooth.h"

@interface UrbanMainViewController ()<UITableViewDataSource,UITableViewDelegate,UrbanHomeDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,CBCentralManagerDelegate>

@property (nonatomic, strong) UIImageView *imageView;//headView
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *stopline;//下滑线
@property (nonatomic, strong) UIView *taskline;//部门
@property (nonatomic, strong) NSMutableArray *recordList;
@property (nonatomic, strong) NSString *numberStop;
@property (nonatomic, assign) NSInteger pageNumber;
@property (nonatomic, assign) NSInteger pageNewsNumber;
@property (nonatomic, strong) NSMutableArray *taskList;
@property (nonatomic, assign) NSInteger typeNumber;
@property (nonatomic, assign) NSInteger advisoryCount;
@property (nonatomic, assign) NSInteger policyCount;

@property (nonatomic, strong) NSString *latitude;//纬度
@property (nonatomic, strong) NSString *longitude;//经度
@property (nonatomic, strong) NSString *where;//
@property (nonatomic, strong) NSString *address;//
@property (nonatomic, strong) BMKLocationService *locationManager;
@property (nonatomic, strong) BMKGeoCodeSearch *searcher;//查询

@property (strong, nonatomic) UrbanBlueTooth *bluetooth;
@property (strong, nonatomic) CBPeripheral *peripheral;
@property (strong, nonatomic) NSMutableArray *listDevices;
@property (strong, nonatomic) CBCentralManager *centralManager;

@property (nonatomic, strong) NSString *flag;

@end

@implementation UrbanMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _recordList = [NSMutableArray new];
    
    _taskList = [NSMutableArray new];
    
    _pageNumber = 1;
    
    _pageNewsNumber = 1;
    
    _typeNumber = 1;
    
    self.listDevices = [NSMutableArray array];
    
    self.bluetooth = [[UrbanBlueTooth alloc]init];
    
    [self.locationManager startUserLocationService];
    
    [self getNumberRecord];
    
    [self getRecordList];
    
    [self creatView];
    
    [self createButton];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];

    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    if ([Storage isLawen]) {
        
        _pageNumber = 1;
        [_recordList removeAllObjects];
        
        [self getNumberRecord];
        [self getRecordList];

        [standfault setObject:@"NO" forKey:@"lawen"];
        [standfault synchronize];
    }
    
    self.centralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil options:nil];
}

- (void)creatView{
    
    _imageView = [TomamaUI createImageView:CGRectMake(0, 0, SCREENW, 0) backGroundImageV:@"blue_bg"];
    _imageView.userInteractionEnabled = YES;
    [self creatImageView];
    [self.view addSubview:_imageView];
    
    UIButton *rightButton = [TomamaUI createRightButton:CGRectMake(0, 0, 80, 44) targ:self sel:@selector(rightButton) titleColor:[UIColor whiteColor] title:@"打印机" image:@"print"];
    UIBarButtonItem *barButtonitem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = barButtonitem;
    
    CGFloat height = 0;
    if (NavBarHeight == 64) {
        height = 49;
    }else{
        height = 83;
    }
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(10*screenW_6, CGRectGetMaxY(_imageView.frame), SCREENW - 20*screenW_6, SCREENH - CGRectGetMaxY(_imageView.frame) - height) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    _tableView.mj_header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
}

- (void)creatImageView
{
    CGFloat height = NavBarHeight;

    UILabel *titleLable = [[UILabel alloc]initWithFrame:CGRectMake(0, StatusBarHeight, SCREENW, 44)];
    titleLable.textAlignment = NSTextAlignmentCenter;
    titleLable.text = @"黄冈-违停执法";
    titleLable.textColor = [UIColor whiteColor];
    titleLable.font = [UIFont systemFontOfSize:18];
    [_imageView addSubview:titleLable];
  
    //违停
    UILabel *numStopLable = [TomamaUI createLabel:CGRectMake(0, 40*screenW_6 + height, SCREENW/2, 30*screenW_6) textAligment:1 font:[UIFont fontWithName:@"TwCenMT-Condensed" size:30*screenW_6] textColor:[UIColor whiteColor] text:_numberStop];
    [_imageView addSubview:numStopLable];
    
    UILabel *stopLable = [TomamaUI createLabel:CGRectMake(0, CGRectGetMaxY(numStopLable.frame) + 11*screenW_6, SCREENW/2, 10*screenW_6) textAligment:1 font:[UIFont systemFontOfSize:10*screenW_6] textColor:[UIColor whiteColor] text:@"车辆违停"];
    [_imageView addSubview:stopLable];
    
    _stopline = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(stopLable.frame) + 11*screenW_6, [TomamaUI getStringWeithtWith:stopLable.text andHeigth:10*screenW_6 andFont:[UIFont systemFontOfSize:10*screenW_6]] + 20*screenW_6, 3*screenW_6)];
    _stopline.backgroundColor = [UIColor whiteColor];
    _stopline.hidden = NO;
    [_imageView addSubview:_stopline];
    _stopline.center = CGPointMake(stopLable.center.x, _stopline.center.y);
    
    UIButton *stopBtn = [TomamaUI createButton:0 Frame:CGRectMake(0, 40*screenW_6 + height, _stopline.frame.size.width, 77*screenW_6) targ:self sel:@selector(stopBtn) titleColor:nil font:nil title:nil image:nil backGroundImage:nil];
    stopBtn.backgroundColor = [UIColor clearColor];
    [_imageView addSubview:stopBtn];
    stopBtn.center = CGPointMake(numStopLable.center.x, stopBtn.center.y);
    //未完成任务
    UILabel *numTaskLable = [TomamaUI createLabel:CGRectMake(SCREENW/2, 40*screenW_6 + height, SCREENW/2, 30*screenW_6) textAligment:1 font:[UIFont fontWithName:@"TwCenMT-Condensed" size:30*screenW_6] textColor:[UIColor whiteColor] text:@"0"];
    [_imageView addSubview:numTaskLable];
    
    UILabel *taskLable = [TomamaUI createLabel:CGRectMake(SCREENW/2, CGRectGetMaxY(numTaskLable.frame) + 11*screenW_6, SCREENW/2, 10*screenW_6) textAligment:1 font:[UIFont systemFontOfSize:10*screenW_6] textColor:[UIColor whiteColor] text:@"未完成任务"];
    [_imageView addSubview:taskLable];
    
    _taskline = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(taskLable.frame) + 11*screenW_6, [TomamaUI getStringWeithtWith:taskLable.text andHeigth:10*screenW_6 andFont:[UIFont systemFontOfSize:10*screenW_6]] + 20*screenW_6, 3*screenW_6)];
    _taskline.backgroundColor = [UIColor whiteColor];
    _taskline.hidden = YES;
    [_imageView addSubview:_taskline];
    _taskline.center = CGPointMake(taskLable.center.x, _taskline.center.y);
    
    UIButton *taskBtn = [TomamaUI createButton:0 Frame:CGRectMake(0, 40*screenW_6 + height, _taskline.frame.size.width, 77*screenW_6) targ:self sel:@selector(taskBtn) titleColor:nil font:nil title:nil image:nil backGroundImage:nil];
    taskBtn.backgroundColor = [UIColor clearColor];
    [_imageView addSubview:taskBtn];
    taskBtn.center = CGPointMake(numTaskLable.center.x, taskBtn.center.y);
    
    _imageView.frame = CGRectMake(0, 0, SCREENW, CGRectGetMaxY(_stopline.frame) + 10*screenW_6);
}

- (void)stopBtn
{
    _typeNumber = 1;
    _stopline.hidden = NO;
    _taskline.hidden = YES;
    
    self.tableView.mj_footer.hidden = YES;
    
    if (_pageNumber == 1) {
        [_recordList removeAllObjects];
        [self getRecordList];
    }else{
        [_tableView reloadData];
    }
}

- (void)taskBtn
{
    _typeNumber = 2;
    _stopline.hidden = YES;
    _taskline.hidden = NO;
    [_recordList removeAllObjects];
    self.tableView.mj_footer.hidden = NO;
    [_tableView reloadData];
}

- (void)rightButton
{
    UrbanPrinterViewController *printer = [UrbanPrinterViewController new];
    [self.navigationController pushViewController:printer animated:YES];
}

#pragma mark - 创建悬浮的按钮

- (void)createButton{
    CGFloat height = StatusBarHeight;
    UIButton *button = [TomamaUI createButton:0 Frame:CGRectMake(SCREENW - 60*screenW_6 - 15*screenW_6, SCREENH - height - 60*screenW_6 - 49, 60*screenW_6, 60*screenW_6) targ:self sel:@selector(resignButton) titleColor:nil font:nil title:nil image:nil backGroundImage:@"icon_zhifa"];
    
    [button setBackgroundColor:[UIColor whiteColor]];
    
    button.layer.cornerRadius = 30*screenW_6;
    
    button.layer.masksToBounds = YES;
    
    [button addTarget:self action:@selector(resignButton) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button];
    
    UIButton *button1 = [TomamaUI createButton:0 Frame:CGRectMake(15*screenW_6, SCREENH - height - 60*screenW_6 - 49, 60*screenW_6, 60*screenW_6) targ:self sel:@selector(jingaoButton) titleColor:nil font:nil title:nil image:nil backGroundImage:@"icon_jingao"];
    
    [button1 setBackgroundColor:[UIColor whiteColor]];
    
    button1.layer.cornerRadius = 30*screenW_6;
    
    button1.layer.masksToBounds = YES;
    
    [button1 addTarget:self action:@selector(jingaoButton) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:button1];
}

- (void)resignButton{
    UrbanLawEnforcementViewController *Lawen = [UrbanLawEnforcementViewController new];
    Lawen.latitude = _latitude;
    Lawen.longitude = _longitude;
    Lawen.where = _where;
    Lawen.address = _address;
    Lawen.flag = @"1";
    [self.navigationController pushViewController:Lawen animated:YES];
}

- (void)jingaoButton{
    UrbanLawEnforcementViewController *Lawen = [UrbanLawEnforcementViewController new];
    Lawen.latitude = _latitude;
    Lawen.longitude = _longitude;
    Lawen.where = _where;
    Lawen.address = _address;
    Lawen.flag = @"3";
    [self.navigationController pushViewController:Lawen animated:YES];
}

- (void)refresh
{
    if (_typeNumber == 1) {
        _pageNumber = 1;
        [_recordList removeAllObjects];
        
    }else{
        
    }
    [self getNumberRecord];
    [self getRecordList];
}

//上拉加载更多
-(void)footerRefresh
{
    if (_typeNumber == 1) {
        _pageNumber++;
        
        [self getRecordList];
    }else{
        
    }
    
    [self getRecordList];
}

#pragma mark - tabledelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _recordList.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor colorWithHexString:@"#f8f8f8"];
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10*screenW_6;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellID = @"HomeCell";
    UrbanHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UrbanHomeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
    cell.delegate = self;
    
    [cell loadData:_recordList[indexPath.section] number:indexPath.section];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [UrbanHomeTableViewCell cellHeight:_recordList[indexPath.section] number:indexPath.section];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)homeWhere:(NSInteger)num
{
    UrbanWhereViewController *where = [UrbanWhereViewController new];
    where.mapType = 0;
    where.latitude = [_recordList[num] objectForKey:@"latitude"];
    where.longitude = [_recordList[num] objectForKey:@"longitude"];
    [self.navigationController pushViewController:where animated:YES];
}

- (void)homePhone:(NSInteger)num
{
    UrbanPhotoViewController *photoVC = [UrbanPhotoViewController new];
    photoVC.imageOne = [_recordList[num] objectForKey:@"image1"];
    photoVC.imageTwo = [_recordList[num] objectForKey:@"image2"];
    [self.navigationController pushViewController:photoVC animated:YES];
}

- (void)printer:(NSInteger)num
{
    _flag = [_recordList[num] objectForKey:@"orderState"];
    _orderNumber = [_recordList[num] objectForKey:@"orderNumber"];
    _plateNumber = [_recordList[num] objectForKey:@"carNumber"];
    if ([[_recordList[num] objectForKey:@"carType"] intValue] == 1) {
        _carType = @"小车";
    }else{
        _carType = @"大车";
    }
    _numPlateColor = [_recordList[num] objectForKey:@"carNumColour"];
    _parkTime = [_recordList[num] objectForKey:@"carParkTime"];
    _addressPr = [NSString stringWithFormat:@"%@%@",[_recordList[num] objectForKey:@"carAddress"],[_recordList[num] objectForKey:@"addressDetails"]];
    
    for (int i = 0; i<_listDevices.count; i++) {
        NSString* uuid = [NSString stringWithFormat:@"%@", [[_listDevices objectAtIndex:i] identifier]];
        uuid = [uuid substringFromIndex:[uuid length] - 12];
        
        if ([[Storage getPrinter] isEqualToString:uuid]) {
            self.peripheral = [_listDevices objectAtIndex:i];
        }
    }
    [self print];
}

- (void)getNumberRecord
{
    NSMutableDictionary *dic = [NSMutableDictionary new];
    [dic setValue:[Storage getToken] forKey:@"user.id"];
    
    [HttpRequest PostrequestUrl:@"jeesite/appInterface/ZfOrderInfo/queryOrderInfo" Dic:dic completion:^(NSDictionary *responseDic)
     {
         if ([responseDic[@"success"] boolValue]) {//请求成功
             self->_numberStop = [NSString stringWithFormat:@"%@",[responseDic objectForKey:@"count"]];
             [self.imageView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
             [self creatImageView];
         }
     }];
}

- (void)getRecordList
{
    [HudHelper showHudWithMessage:@"..." toView:self.view];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        NSMutableDictionary *dic = [NSMutableDictionary new];
        [dic setValue:[Storage getToken] forKey:@"user.id"];
        [dic setValue:[NSString stringWithFormat:@"%ld",(long)self->_pageNumber] forKey:@"pageNo"];
        [dic setValue:@"10" forKey:@"pageSize"];
        
        [HttpRequest PostrequestUrl:@"jeesite/appInterface/ZfOrderInfo/queryRecord" Dic:dic completion:^(NSDictionary *responseDic){
            dispatch_async(dispatch_get_main_queue(), ^{
                [HudHelper hideHudToView:self.view];
                NSLog(@"respond:%@",responseDic);
                if ([responseDic[@"success"] boolValue]) {//请求成功
                    
                    if (self->_typeNumber == 1) {
                        [self->_recordList addObjectsFromArray:[[responseDic objectForKey:@"data"] objectForKey:@"list"]];
                        
                        if([[[responseDic objectForKey:@"data"] objectForKey:@"count"] floatValue]/10 <= self->_pageNumber){
                            self.tableView.mj_footer.hidden = YES;
                        }else{
                            self.tableView.mj_footer.hidden = NO;
                        }
                    }else{
                        
                    }
                    
                    [self->_tableView reloadData];
                }
                
                if ([self->_tableView.mj_header isRefreshing]) {
                    [self->_tableView.mj_header endRefreshing];
                }
                if ([self->_tableView.mj_footer isRefreshing]) {
                    
                    [self->_tableView.mj_footer endRefreshing];
                }
            });
        }];
    });
}

//定位
- (BMKLocationService *)locationManager
{
    if (!_locationManager)
    {
        _locationManager = [[BMKLocationService alloc] init];
        _locationManager.delegate = self;
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    }
    return _locationManager;
}

//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [self addSearch:userLocation.location.coordinate];
    [_locationManager stopUserLocationService];//停止定位
}

-(void)addSearch:(CLLocationCoordinate2D)pt{
    _searcher =[[BMKGeoCodeSearch alloc]init];
    _searcher.delegate = self;
    //发起反向地理编码检索
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeoCodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [_searcher reverseGeoCode:reverseGeoCodeSearchOption];
    
    if(flag)
    {
        _latitude = [NSString stringWithFormat:@"%f",pt.latitude];
        _longitude = [NSString stringWithFormat:@"%f",pt.longitude];
        NSLog(@"反geo检索发送成功");
    }
    else
    {
        NSLog(@"反geo检索发送失败");
    }
}

-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (error == BMK_SEARCH_NO_ERROR) {
        self.where = [result.poiList[0] city];
        self.address = result.address;
    }
    else {
        NSLog(@"抱歉，未找到结果");
    }
}

//开始查看服务, 蓝牙开启
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            [self BlueState];
            break;
            
        case CBManagerStatePoweredOff:
            [ToolViewVC addKeyAlterViewController:@"蓝牙未打开，请打开蓝牙" Controller:self];
            break;
            
        case CBManagerStateUnauthorized:
            [ToolViewVC addKeyAlterViewController:@"蓝牙未授权" Controller:self];
            break;
            
        case CBManagerStateUnsupported:
            [ToolViewVC addKeyAlterViewController:@"设备不支持蓝牙" Controller:self];
            break;
            
        case CBManagerStateResetting:
            [ToolViewVC addKeyAlterViewController:@"蓝牙重置状态" Controller:self];
            break;
            
        case CBManagerStateUnknown:
            [ToolViewVC addKeyAlterViewController:@"蓝牙处于未知状态" Controller:self];
            break;
            
        default:
            break;
    }
}

- (void)wrapPrintDatas
{
    [self.bluetooth StartPage:560 pageHeight:888 ];
    [self.bluetooth TextCenter:@"违法停车告知单" font:24 x:125 y:20];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"编    号:%@",_orderNumber] font:24 x:30 y:90];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"车辆牌号:%@",_plateNumber] font:24 x:30 y:130];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"车辆类型:%@",_carType] font:24 x:30 y:170];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"号牌颜色:%@",_numPlateColor] font:24 x:30 y:210];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"停放时间:%@",_parkTime] font:24 x:30 y:250];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"停放地点:%@",_addressPr] font:24 x:30 y:290];
    [self.bluetooth TextLeft:@"   上述时间、地点，该机动车未在停车场或道路" font:24 x:30 y:350];
    [self.bluetooth TextLeft:@"停车泊位内停放，违反了《中华人民共和国道路安" font:24 x:30 y:390];
    [self.bluetooth TextLeft:@"全交通法》第56条的规定，违法行为已被拍照取证" font:24 x:30 y:430];
    [self.bluetooth TextLeft:@"。根据《湖北省实施<中华人民共和国道路交通安" font:24 x:30 y:470];
    [self.bluetooth TextLeft:@"全法>办法》第69条第十三项的规定，请自收到本" font:24 x:30 y:510];
    [self.bluetooth TextLeft:@"告知单5日内到西湖一路33号市城管执法局一楼服" font:24 x:30 y:550];
    [self.bluetooth TextLeft:@"务大厅接受处理。" font:24 x:30 y:590];
    [self.bluetooth TextLeft:[self getTimes] font:24 x:380 y:650];
    [self.bluetooth zp_darwQRCode:30 y:650 unit_width:4 text:@"https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI2MTQ0MDA2Mg=="];
    [self.bluetooth TextLeft:@"关注“东坡城曦”" font:24 x:30 y:805];
    
    [self.bluetooth end];
}

- (void)wrapPrintJinGaoDatas
{
    [self.bluetooth StartPage:560 pageHeight:888 ];
    [self.bluetooth TextCenter:@"温 馨 提 示" font:24 x:125 y:20];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"编    号:%@",_orderNumber] font:24 x:30 y:90];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"车辆牌号:%@",_plateNumber] font:24 x:30 y:130];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"车辆类型:%@",_carType] font:24 x:30 y:170];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"号牌颜色:%@",_numPlateColor] font:24 x:30 y:210];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"停放时间:%@",_parkTime] font:24 x:30 y:250];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"停放地点:%@",_address] font:24 x:30 y:290];
    [self.bluetooth TextLeft:@"   上述时间、地点，该机动车未在停车场或道路" font:24 x:30 y:350];
    [self.bluetooth TextLeft:@"停车泊位内停放，请您看到提示后迅速将车辆转移" font:24 x:30 y:390];
    [self.bluetooth TextLeft:@"到规定地点停放。" font:24 x:30 y:430];
    [self.bluetooth TextLeft:@"   节日期间，为了您有一个愉快的心情，本次不" font:24 x:30 y:470];
    [self.bluetooth TextLeft:@"予处罚，如再次违停将依法处罚，请您理解，支持" font:24 x:30 y:510];
    [self.bluetooth TextLeft:@"和配合，祝您快乐！" font:24 x:30 y:550];
    [self.bluetooth TextLeft:[self getTimes] font:24 x:380 y:610];
    [self.bluetooth zp_darwQRCode:30 y:610 unit_width:4 text:@"https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI2MTQ0MDA2Mg=="];
    [self.bluetooth TextLeft:@"关注“东坡城曦”" font:24 x:30 y:765];
    
    [self.bluetooth end];
}

- (NSString *)getTimes
{
    // 日期格式化类
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    // 设置日期格式(为了转换成功)
    fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    
    // NSString * -> NSDate *
    NSDate *date = [fmt dateFromString:_parkTime];
    
    // 利用NSCalendar处理日期
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *cmps = [calendar components:unit  fromDate:date];
    
    NSString *time = [NSString stringWithFormat:@"%ld年%ld月%ld日",(long)cmps.year,(long)cmps.month,(long)cmps.day];
    
    return time;
}

- (void)print{
    
    /* Byte byte[] = {0x0d,0x0a};
     NSData *adata = [[NSData alloc] initWithBytes:byte length:2];
     [self.bluetooth open:self.peripheral];
     [self.bluetooth flushRead];
     [self.bluetooth writeData:adata];
     [self.bluetooth close];
     */
    if (self.peripheral) {
        [self.bluetooth open:self.peripheral];
        [self.bluetooth flushRead];
        
        if ([_flag integerValue] == 3) {
            [self wrapPrintJinGaoDatas];
        }else{
            [self wrapPrintDatas];
        }
        [self sendPrintData];
        [self.bluetooth reset];
        [self.bluetooth close];
    }else{
        UrbanPrinterViewController *printer = [UrbanPrinterViewController new];
        printer.orderNumber = _orderNumber;
        printer.plateNumber = _plateNumber;
        printer.carType = _carType;
        printer.numPlateColor = _numPlateColor;
        printer.parkTime = _parkTime;
        printer.address = _addressPr;
        printer.flag = _flag;
        [self.navigationController pushViewController:printer animated:YES];
    }
}

-(void)sendPrintData{
    
    int r = self.bluetooth.dataLength;
    
    NSData *data = [self.bluetooth getData:r];
    
    [self.bluetooth writeData:data];
}

- (void)BlueState
{
    if(_listDevices != nil){
        _listDevices = nil;
        _listDevices = [NSMutableArray array];
    }
    
    BLOCK_CALLBACK_SCAN_FIND callback =
    ^( CBPeripheral*peripheral)
    {
        [self.listDevices addObject:peripheral];
        NSLog(@"scan find: %@",self.listDevices );
        
        NSMutableArray *listAry = [[NSMutableArray alloc]init];
        for (NSString *str in self.listDevices) {
            if (![listAry containsObject:str]) {
                [listAry addObject:str];
            }
        }
        
        for (int i = 0; i < listAry.count; i++) {
            if (![[listAry objectAtIndex:i] name]) {
                [listAry removeObjectAtIndex:i];
            }
        }
        
        self.listDevices = listAry;
    };
    
    [self.bluetooth scanStart:callback];
    
    double delayInSeconds = 5.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds* NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self.bluetooth scanStop];
    });
}

         
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
